package controllers;

import dto.BannerDto;
import dto.BannerType;
import models.Banner;
import models.crudsiena.SienaSupport;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;
import services.BannerService;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Gipxy group
 * Date: 5/9/12
 */
@With(Secure.class)
public class Banners extends CRUD{
    public static void list(int page, String filterField, String filterValue, String orderBy, String order) {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }

        List<? extends SienaSupport> objects = type.findPage(page, filterField, filterValue, orderBy, order);
        Long count = type.count(filterField, filterValue);
        Long totalCount = type.count(null, null);
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
    }

    public static void save(BannerDto dto) throws Exception {
        if (dto.id==null) {
            if (BannerService.isExisted(dto.code, dto.language)) {
                String err = "Da ton tai App voi code=" + dto.code + ", language=" + dto.language;
                flash.error(err);
                renderTemplate("Admin/error.html");
            }
        }

        BannerService.merge(dto);
        redirect("Banners.list");
    }

    public static void input(Long id) {
        Banner app = (id == null) ? new Banner() : Banner.getByKey(Banner.class, id);
        BannerDto dto = BannerService.createDto(app);
        List<BannerType> allBannerTypes = Arrays.asList(BannerType.all);
        render(dto, allBannerTypes);
    }

    public static void show(String id) {
        redirect("Banners.input", id);
    }
    

}
